<?php

namespace app\admin\controller\wx;

use app\admin\model\agent\Info;
use app\admin\model\Assistant;
use app\admin\model\halt\Cate;
use app\admin\validate\AgentInfo;
use app\common\controller\Backend;
use app\common\model\Serial;
use EasyWeChat\Factory;
use PHPExcel;
use PhpOffice\PhpSpreadsheet\Calculation\Exception;
use think\Db;

/**
 * 网销订单
 *
 * @icon fa fa-circle-o
 */
class Wxorder extends Backend
{

    /**
     * Wxorder模型对象
     * @var \app\admin\model\Wxorder
     */
    protected $model = null;
    protected $modelInfo = null;
    protected $redis = null;
    protected $modelImportLog = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Wxorder;
        $this->modelInfo = new \app\admin\model\Wxorderinfo();
        $this->modelImportLog = new \app\admin\model\Wximportlog();
        $this->view->assign('stateList',$this->model->getStateList());
    }

    /**
     * 提分超市订单同步
     * @return string
     * @throws \think\Exception
     */
    public function config()
    {
        if($this->request->isAjax())
        {
            $wxorder = new \app\api\controller\WxOrder();
            $param = $this->request->request('row/a');
            if(!$param['strat']) $this->error('请选择同步时间。');
            $v = str_replace(' - ', ',', $param['strat']);
            $arr = array_slice(explode(',', $v), 0, 2);
            $wxorder->getOrder(strtotime($arr[0]),strtotime($arr[1]),$this->auth->username);
        }
        return $this->view->fetch();
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                if(!$params['agent_id'])
                {
                    $this->error('请选择代理商');
                }
                //查询代理商  验证文件
                $agent = Info::get($params['agent_id']);
                if(!$agent['excle_array'])
                {
                    $this->wxmsg("《".$agent['agent_name'].'代理商》还没有添加新的模板'."\n操作人：".$this->auth->username."\n 时间：".date('Y-m-d H:i:s',time()));
                    $this->error('代理商还没有添加模板数据！');
                }
                $filePath = ROOT_PATH . DS . 'public' . DS . $params['files'];
                if (!is_file($filePath)) {
                    $this->error(__('No results were found'));
                }
                $createtime = date('Y-m-d H:i:s',time());
                $lastId = $this->model->max('id');
                //获取Excel数据
                $list = $this->upgrade($agent['excle_array'],$filePath);
                //商品名称组装
                $list = $this->GdoodsName($list,$agent['id']);
                // 启动事务
                Db::startTrans();
                //商品规格  数据过滤截取
                $logId = $this->modelImportLog->insertGetId([
                    'agent_id'=>$agent['id'],
                    'createtime'=>time(),
                    'updatetime'=>time(),
                ]);
                list($order,$orderInfo) = $this->filtration($list,$agent['id'],$logId);
                try {
                    //开启事务回滚
                    $this->model->saveAll(array_filter($order));
                    $this->modelInfo->saveAll(array_filter($orderInfo));
                    //查询需要拆分的订单
//                    $this->splitOrder($lastId);
                    //查询需要合并北京以外的订单。
//                    $this->mergeOrder($lastId);
                    //查询需要合并北京的订单。
//                    $this->bjMergeOrder($lastId);
                    // 提交事务
                    Db::commit();
                    $endtime  = date('Y-m-d H:i:s',time());
                    $listIds = $this->model->where('log_id','=',$logId)->select();
                    $orderIds = [];
                    foreach ($listIds as $ite)
                    {
                        $orderIds[] = $ite->id;
                    }
                    $this->modelImportLog->where('id','=',$logId)->update(['order_ids'=>implode(',',$orderIds)]);
                    unset($orderIds,$listIds);
                    \app\admin\model\Wxorder::msg([
                        'moban'=>'dddr',
                        'id'=>$logId,
                        'agent_name'=>Info::getName($agent['id']),
                        'createtime'=>date('Y-m-d H:i:s',time())
                    ]);
                    unset($createtime,$endtime);
                } catch (\think\exception\PDOException $exception) {
                    // 回滚事务
                    Db::rollback();
                    $this->wxmsg('订单导入报错：'.$exception->getMessage()."\n操作人：".$this->auth->username."\n 时间：".date('Y-m-d H:i:s',time()));
                    $this->error($exception->getMessage());
                }

                $this->success();
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    protected function GdoodsName($list = [],$agentId = 0)
    {
        //网购微店
        if($agentId == 87)
        {
            foreach ($list as &$item)
            {
                $tempName = array_filter(explode(']',$item['goods_name']));
                $item['goods_name'] = '';
                foreach ($tempName as $key=>$v)
                {
                    //微店
                    $temp = explode(':',$v);
                    preg_match_all("/([^ ]+)/u",trim($temp[0]),$names);
                    $name1 = str_replace(';','',$names[1]);
                    $item['goods_name'] .=$name1[1];
                    $item['goods_name'] .='['.$temp[1].']';
                    unset($name1,$names,$temp);
                }
            }
        }
        //网购有赞
        if($agentId == 83)
        {
            foreach ($list as &$item)
            {
                $tempName = array_filter(explode(';',$item['goods_name']));
                $item['goods_name'] = '';
                foreach ($tempName as $v)
                {
                    $temp = explode(')',$v);
                    $name = explode('(',$temp[0]);
                    $num = explode('(',$temp[1]);
                    $item['goods_name'] .=str_replace('-','',$name[1]);
                    $num1 = str_replace('件','',$num[1]);
                    $item['goods_name'] .= '['.$num1.']';
                    $item['goods_name'] = str_replace('件','',$item['goods_name']);
                }
            }
        }
        //家有小学生
        if($agentId == 75)
        {
            foreach ($list as $k=>&$item)
            {
                $item['order_sn'] = 'XXS'.time().$agentId.mt_rand(1,999).$k; //编辑一个订单号
                $item['xdtime'] = date('Y-m-d',time());//获取当前时间
                $tempName = array_filter(explode(']',$item['goods_name']));
                $item['goods_name'] ='';
                foreach ($tempName as $key=>$v)
                {
                    $zhi = '';
                    if(strpos($v,'六三') !==  false)
                    {
                        $v = substr($v,strpos($v,'六三'));
                    }
                    if(strpos($v,'五四') !==  false)
                    {
                        $v = substr($v,strpos($v,'五四'));
                    }
                    $v = str_replace(' ','',$v);
                    $temp = explode(':',$v);
                    $temp[0] = str_replace('[数量','',$temp[0]);
                    $temp[0] = str_replace(';','',$temp[0]);
                    //微店
                    if(count($temp) > 1)
                    {
                        $item['goods_name'] .=$temp[0];//倒数第二个
                        $item['goods_name'] .='['.$temp[1].']';
                    }
                    unset($name1,$names,$temp);
                }
            }
        }
        //球妈
        if($agentId == 73)
        {
            foreach ($list as &$item)
            {
                $item['xdtime'] = date('Y-m-d',time());//获取当前时间
                $tempName = array_filter(explode(']',$item['goods_name']));
                $item['goods_name'] = '';
                foreach ($tempName as $v)
                {
                    //微店 2.0
                    $temp = explode(':',$v);
                    preg_match_all("/([^ ]+)/u",trim($temp[0]),$names);
                    $name1 = str_replace(';','',$names[0]);
                    $item['goods_name'] .=$name1[0];
                    $item['goods_name'] .='['.$temp[1].']';
                    unset($name1,$names,$temp);
                }
            }
        }
        //山珊
        if($agentId == 1)
        {
            foreach ($list as &$item)
            {
                $tempName = array_filter(explode(']',$item['goods_name']));
                $item['goods_name'] = '';
                foreach ($tempName as $v)
                {
                    //微店 1.0
                    $temp = explode(':',$v);
                    preg_match_all("/([^ ]+)/u",trim($temp[0]),$names);
                    $name1 = str_replace(';','',$names[1]);
                    $item['goods_name'] .=$name1[1];
                    $item['goods_name'] .='['.$temp[1].']';
                    unset($name1,$names,$temp);
                }
            }

        }
        //选课101  单商品
        if($agentId == 66)
        {
            foreach ($list as &$item)
            {
                $item['goods_name'] .='['.$item['num'].']';
                $item['xdtime'] = date('Y-m-d',time());//获取当前时间
                unset($item['num']);
            }
        }
        //桐妈  单商品
        if($agentId == 65)
        {
            foreach ($list as $k=>&$item)
            {
                $xdtime = str_replace('月','-',$item['xdtime']);
                $item['goods_name'] = str_replace(';','',$item['goods_name']);
                $item['xdtime'] = date('Y',time()).'-'.$xdtime;
                $tempName = array_filter(explode(']',$item['goods_name']));
                $item['goods_name'] = '';
                foreach ($tempName as $key=>$v)
                {
                    //微店
                    $temp = explode('[',$v);
                    $item['goods_name'] .=$temp[0];
                    $num = isset($temp[1]) ? $temp[1]:1;
                    $item['goods_name'] .='['.$num.']';
                    $item['goods_name'] = str_replace('，','',$item['goods_name']);
                    if(!isset($item['order_sn']))  $item['order_sn'] = 'TM'.time().$agentId.mt_rand(1,999).$k; //编辑一个订单号
                    unset($name1,$names,$temp);
                }
            }
        }
        //诗云文化 单商品
        if ($agentId == 115)
        {
            foreach ($list as &$item)
            {
                $item['goods_name'] .="[{$item['num']}]";
                $item['goods_name'] = str_replace('-','',$item['goods_name']);
                unset($item['num']);
            }
        }
        //花生地  单商品  第二次改
        if($agentId == 121)
        {
            foreach ($list as &$item) {
                if(!isset($item['goods_name']) || !$item['goods_name'])
                {
                    $this->error("获取不到商品名称，表不合格！");
                }
                $name = explode('，',$item['goods_name']);
                if(count($name) == 2)
                {
                    $item['goods_name'] = $name[1].$name[0].'[1]';
                }
                if(count($name) == 3){
                    $item['goods_name'] = $name[2].$name[1].$name[0].'[1]';
                }
                $item['goods_name'] = str_replace('年级:','',str_replace('规格:','',str_replace('学制:','',$item['goods_name'])));
            }
        }
        //COCO 单商品
        if($agentId == 64)
        {
            foreach ($list as $k=>&$item) {
                $item['order_sn'] = 'COCO'.time().$agentId.mt_rand(1,999).$k; //编辑一个订单号
                $item['xdtime'] = date('Y-m-d',time());//获取当前时间
                $item['goods_name'] = str_replace('；','',$item['goods_name'])."[1]";
            }
        }
        //星欢 单商品
        if($agentId == 103)
        {
            foreach ($list as &$item) {
                $item['goods_name'] =$item['goods_name'].="[{$item['num']}]";
                unset($item['num']);
            }
        }
        //沈小妮  单商品  于婷婷给的模板
        if($agentId == 122)
        {
            foreach ($list as &$item) {
                $item['goods_name'] .= $item['nj'] .= $item['xg'].= "[{$item['num']}]";
                $item['xdtime'] = date('Y-m-d',time());
                unset($item['nj'],$item['xg'],$item['num']);
            }
        }
        //小舵手  69 单商品 删除头部两行   绘本课堂小学语文教材全新教辅 (六三（部编版，小学6年初中3年）,全套:A学习书+B练习书+C素材书+年级阅读,四年级（下）) [1 * 228.24
        if($agentId == 69)
        {
            foreach ($list as &$item) {
                $item['xdtime'] = date('Y-m-d',time());
                $tempName = array_filter(explode(']',trim($item['goods_name'])));
                $item['goods_name'] = '';
                $item['amount'] = 0;
                foreach ($tempName as $key=>$v)
                {
                    $arr = explode('[',$v);
                    $num = explode('*',$arr[1]);
                    $item['goods_name'] .= substr($arr[0],(strpos($arr[0],"(") + 1),(strrpos($arr[0],")") - strpos($arr[0],"("))-1);
                    $item['goods_name'] = trim(str_replace(',','',$item['goods_name']))."[".trim($num[0])."]";
                    $item['amount'] += trim($num[1]);
                }
            }

        }
        //大手牵小手  李莹 单商品
        if($agentId == 49)
        {
            foreach ($list as &$item) {
                $item['goods_name'] = str_replace(';','',$item['goods_name']);
                $item['goods_name'] .= "[{$item['num']}]";
              unset($item['num']);
            }
        }
        //崩豆  单商品
        if($agentId == 67)
        {
            foreach ($list as $k=>&$item) {
                if(!isset($item['order_sn']))
                {
                    $item['order_sn'] = 'bdqz'.time().$agentId.mt_rand(1,999).$k; //编辑一个订单号
                }
                $item['goods_name'] = trim($item['goods_name']);
                $item['goods_name'] .="[{$item['num']}]";
                $item['xdtime'] =date('Y',time()).'-'.$item['xdtime'];
                unset($item['num']);
            }

        }
        //有时商贸 单个商品
        if($agentId == 68)
        {
            foreach ($list as &$item) {
                $item['goods_name'] = str_replace(';','',$item['goods_name']);
                $item['goods_name'] .="[{$item['num']}]";
                unset($item['num']);
            }
        }
        //慧童空间  单个商品
        if($agentId == 129)
        {
            foreach ($list as &$item) {
                $item['goods_name'] = str_replace(';','',$item['goods_name'])."[{$item['num']}]";
                $item['xdtime'] = date('Y-m-d',time());
                unset($item['num']);
            }
        }
        //海淀胖爸  单个商品
        if($agentId == 102)
        {
            foreach ($list as &$item) {
                $name = explode('，',$item['goods_name']);
                if(count($name) == 2)
                {
                    $item['goods_name'] = $name[1].$name[0].'[1]';
                }
                if(count($name) == 3){
                    $item['goods_name'] = $name[2].$name[1].$name[0].'[1]';
                }
                if(count($name) == 1){
                    $item['goods_name'] = $name[0].'[1]';
                }
                $item['goods_name'] = str_replace('年级:','',str_replace('规格:','',str_replace('学制:','',$item['goods_name'])));
                $item['goods_name'] = str_replace('全套：','',$item['goods_name']);
            }
        }
        //网购京东
        if($agentId == 79)
        {
            $test = array_column($list,'order_sn','');
            // 去掉重复数据的数组
            $unique_arr = array_unique ($test);
            // 获取重复数据的数组
            $repeat_arr = array_diff_assoc($test,$unique_arr);
            foreach ($list as &$item) {
                $item['phone']  = str_replace('*','',$item['phone']);
                if (!$item['phone']) $this->error('请填写客户手机号码');
                preg_match_all("/([^ ]+)/u",trim($item['goods_name']),$tempName);
                $item['goods_name'] = '';
                foreach ($tempName[0] as $k=>$v) {
                    if($k == 0) continue;
                    $item['goods_name'] .=$v;
                }
                $item['goods_name'] .="[{$item['num']}]";
                unset($tempName,$item['num']);
            }
            foreach ($repeat_arr as $key=>$value)
            {
                if($value == $list[$key - 1]['order_sn']){
                    $list[$key-1]['goods_name'] .= $list[$key]['goods_name'];
                    unset($list[$key]);
                }
            }
        }
        //灯心草
        if($agentId == 149)
        {
            foreach ($list as $k=>&$item) {
                $name = explode(']',$item['goods_name']);
                $item['goods_name'] = '';
                foreach (array_filter($name) as &$va)
                {
                    $name1 = explode('[',$va);
                    $item['goods_name'] .=$name1[0].'['.$name1[1].']';
                    if(!isset($item['order_sn']))  $item['order_sn'] = 'XK'.time().$agentId.mt_rand(1,999).$k; //编辑一个订单号
                }
                unset($item['num']);
            }
        }
        //蚂蚁书屋
        if($agentId == 144)
        {
            foreach ($list as $k=>&$item) {
                $name = str_replace(';','',$item['goods_name']);
                $item['goods_name'] = $name."[".$item['num']."]";
                if(!isset($item['order_sn']))  $item['order_sn'] = 'MAYI'.time().$agentId.mt_rand(1,999).$k; //编辑一个订单号
                $item['xdtime'] = date('Y-m-d',time());//获取当前时间
                unset($item['num']);
            }
        }
        //麦豆严选
        if($agentId == 63)
        {
            foreach ($list as $k=>&$item) {
                $item['goods_name'] = $item['xuezhi'].$item['nianji'].$item['goods_name']."[".$item['num']."]";
                $item['goods_name'] = str_replace(' ','',$item['goods_name']);
                unset($item['num'],$item['xuezhi'],$item['nianji']);
            }

        }
        //芒果
        if($agentId == 145)
        {
            foreach ($list as $k=>&$item) {
                $item['goods_name'] = $item['goods_name']."[".$item['num']."]";
                $item['goods_name'] = str_replace('+','',$item['goods_name']);
                if(!isset($item['order_sn']))  $item['order_sn'] = 'MANGGUO'.time().$agentId.mt_rand(1,999).$k; //编辑一个订单号
                $item['xdtime'] = date('Y-m-d',time());//获取当前时间
                unset($item['num'],$item['xuezhi'],$item['nianji']);
            }
        }
        //童趣
        if($agentId == 139)
        {
            foreach ($list as &$item)
            {
                $result = array_filter(explode(')',$item['goods_name']));
                $str = explode('(',$result[0])[1];
                $name = str_replace(';','',$str);
                $num = str_replace('(','',$result[1]);
                $item['goods_name'] = $name."[{$num}]";
            }
        }
        //寓乐童年
        if($agentId == 143)
        {
            foreach ($list as &$item)
            {
                $item['goods_name'] = str_replace('-','',$item['goods_name']);
                $item['goods_name'] .="[{$item['num']}]";
                unset($item['num']);
            }
        }
        //赋能妈妈微店
        if($agentId == 137)
        {
            foreach ($list as &$item)
            {
                $tempName = array_filter(explode(']',$item['goods_name']));
                $item['goods_name'] = '';
                foreach ($tempName as $key=>$v)
                {
                    //微店
                    $temp = explode('[',$v);
                    if(count($temp) == 1)
                    {
                        $item['goods_name'] .=$temp[0];
                        $item['goods_name'] .='['.$item['num'].']';;
                    }else{
                        $item['goods_name'] .=$temp[0];
                        $item['goods_name'] .='['.$temp[1].']';
                    }
                    unset($item['num'],$temp);
                    $item['goods_name'] = str_replace(';','',$item['goods_name']);
                }
            }
        }
        //抖音
        if($agentId == 135)
        {
            foreach ($list as &$item)
            {
                if(isset($item['num'])){
                    $item['goods_name']= $item['goods_name'].'['.$item['num']."]";
                    $item['order_sn'] = str_replace('\'','',$item['order_sn']);
                    unset($item['num']);
                }
                $item['xdtime'] = time();
            }
        }
        //书香
        if($agentId == 150)
        {
            foreach ($list as &$item)
            {
                $item['goods_name'] = str_replace(" ",'',trim($item['goods_name']));
                $tempName = array_filter(explode(']',$item['goods_name']));
                $item['goods_name'] = '';
                foreach ($tempName as $val)
                {
                    $name1 = array_filter(explode('[',$val));
                    if(count($name1) > 1)
                    {
                        $item['goods_name'] .= $name1[0].'['.$name1[1].']';
                    }else{
                        $item['goods_name'] .= $name1[0].'['.$item['num'].']';
                    }
                }
                unset($item['num']);
            }
        }
        $order_sn = [];
        foreach ($list as &$v)
        {
            $order_sn[] = $v['order_sn'];
            if(!isset($v['address']))
            {
                $this->error("收件人".$v['receipt'].'获取不到收货地址！');
            }
            if(!isset($v['receipt']))
            {
                $this->error("收件人姓名获取不到");
            }
            if(!isset($v['phone']))
            {
                $this->error("收件人".$v['receipt'].'获取不到手机号码！');
            }
            if(!isset($v['xdtime']))
            {
                $v['xdtime'] = time();
            }
            if(!isset($v['goods_name']) || !$v['goods_name'])
            {
                $this->error("获取不到商品名称，表不合格！");
            }
            $v['phone'] = trim($v['phone']);
            $v['phone'] = str_replace(' ','',$v['phone']);
            $v['address'] = str_replace(' ','',$v['address']);
            //带M就发旧的。不带就发新的
            if(strpos($v['goods_name'],'M') === false)
            {
                $v['new'] = '2020';
            }else{
                $v['goods_name'] = str_replace('M','',$v['goods_name']);
                $v['new'] = '2019';
            }
            $v['goods_name'] = $this->model->kx($v['goods_name']);
        }
        if (count($order_sn) != count(array_unique($order_sn)))
        {
            $this->error("请检查重复的订单号！");
        }

//        if($agentId == 121)
//        {
//            foreach ($list as $item) {
//                print_r($item);exit;
//            }
//        }
        //张伟测试
//        if($agentId == 131)
//        {
//            foreach ($list as $value)
//            {
//                //是否有多科选择
//                if(strstr($value['goods_name'], '('))
//                {
//                    echo "多科";
//                }
//            }
//            echo "<pre>";
//            print_r($list);exit;
//        }
        return $list;
    }


    /**
     * 商品验证
     * @param array $order
     * @param $agent_id
     * @return array
     * @throws \think\exception\DbException
     */
    protected function filtration($order = [],$agent_id,$logId)
    {
        $productInsert = [];
        $error = [];
        $errordata = [];
        foreach ($order as $currentRow=>&$item)
        {
            //商品规格拆分
            /**   商品名称拆分开始
             *  列如 六三制四年级下字典[1]
             *   用]结尾的拆分数组  获取商品名称 进行遍历获取更多的商品 跟数量
             */
            $akg = 0;
            $product = [];
            foreach (array_filter(explode(']',$item['goods_name'])) as $key=>$value)
            {
                // $tmp[0] 为商品名称  $tmp[1] 数量
                $tmp = explode('[',$value);
                $duoke = '';
                $str = $tmp[0];
                if(strpos($str,'(',0) > 0)
                {
                    preg_match('/(?<=\().*?(?=\))+/', $tmp[0], $ok);
                    $duoke = $ok[0];
                    $tmp[0] = str_replace("({$duoke})",'',$tmp[0]);
                }

                if($item['new'] == 2020)
                {
                    $Product = \app\admin\model\Wxproduct::get(['name'=>$tmp[0]]);
                    if($Product){
                        $Product->type == 3 || $Product->type == 18 ? $tmp[0].=$item['new'] :'';
                    }
                }

                if($Product = \app\admin\model\Wxproduct::get(['name'=>$tmp[0]]))
                {
                    $product[] = [
                        'order_sn'=>$item['order_sn'],
                        'goods_name'=>$tmp[0],
                        'num'=>$tmp[1],
                        'kg'=>$Product->kg,
                        'wxproduct_id'=>$Product->id,
                        'price'=>$Product->ministrial * $tmp[1],
                        'unit'=>$Product->unit,
                        'dk'=>$duoke,
                    ];
                    $akg += ($Product->kg * $tmp[1]);
                    $item['weigh'] = $Product->weigh;
                    unset($duoke,$ok);
                }else{
//                    $this->error("第".($currentRow+2).'行，产品名称有误。'.$tmp[0]);
                    $error[$currentRow+2][$key+$currentRow] = "第".($currentRow+2).'行，'.$tmp[0];
                    $errordata[$currentRow+2][$key+$currentRow] = $tmp[0];
                }
            }
            $item['akg'] = $akg;
            $item['agent_id'] = $agent_id;
            $item['log_id'] = $logId;
            unset($item['goods_name'],$item['new']);
            $productInsert[] = $this->rsa($item,$product);
        }

        if($error)
        {
            //生成Excel表发给张静
            $dataError = array_merge(...$errordata);
            $html = '';
            foreach (array_merge(...$error) as $value)
            {
                $html .='<ul>';
                $html .='<li>'.$value;
                $html .='</li>';
                $html .='</ul>';
            }
            $this->excelSend($dataError,$agent_id);
            $this->error('产品名称有误','',$html);
        }
        $orderInfo = array();
        foreach($productInsert as $key => $_gc_class){
            foreach ($_gc_class as $value)
            {
                unset($value['unit']);
                $orderInfo[] = $value;
            }
        }
        return [$order, $orderInfo];
    }


    protected function excelSend($data = [],$agent_id)
    {
        $info = Info::get($agent_id);
        $objPHPExcel = new PHPExcel();
        $row = $objPHPExcel->setactivesheetindex(0);
        //列为文本
        $row->getStyle('A')->getNumberFormat()
            ->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);
        $row->setTitle("0");
        foreach ($data as $k=>$v)
        {
            $row->setcellvalue('A'.($k+2), $v);
            $row->getColumnDimension('A')->setWidth(50);
        }
        $objWriter = new \PHPExcel_Writer_Excel2007($objPHPExcel);
        $date = date('Y-m-d H-i-s',time());
        $filename = $this->auth->username.'-'.$info->agent_name.'-'.$date.'.xlsx';
        $objWriter->save('./agent/xlsx/'.$filename);
        $config = Assistant::config();
        $app = Factory::work($config);
        $path = ROOT_PATH . 'public/agent/xlsx/'.$filename;
        $res = $app->media->uploadFile($path);
        //发送文件给操作人
        if($res['errcode'] == 0 ){
//                unlink($path);
            $token = $app->access_token->getToken();//获取企业微信token
            $url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={$token['access_token']}";
            $params = [
                'touser'=>'yangliu|ZhangJing02|ZhangWei',
                'msgtype'=>'file',
                'agentid'=>$config['agent_id'],
                'file'=>[
                    'media_id'=>$res['media_id']
                ],
                'safe'=>0
            ];
            $response = \fast\Http::post($url,json_encode($params));
            $response = json_decode($response,true);
            if($response['errcode'] != 0)
            {
                return false;
            }
        }
    }
    /**
     * 获取excel 数据
     * @param $excle
     * @param $filePath
     * @return array
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     * @throws \think\exception\DbException
     */
    protected function upgrade($excle, $filePath)
    {
        ini_set('max_execution_time', '0');
        $createtime = date('Y-m-d H:i:s', time());
        $PHPReader = new \PHPExcel_Reader_Excel2007();
        if (!$PHPReader->canRead($filePath)) {
            $PHPReader = new \PHPExcel_Reader_Excel5();
            if (!$PHPReader->canRead($filePath)) {
                $PHPReader = new \PHPExcel_Reader_CSV();
                if (!$PHPReader->canRead($filePath)) {
                    $this->error(__('Unknown data format'));
                }
            }
        }
        $fieldArr = array_column(json_decode(unserialize($excle), true), 'key', 'value');
        $PHPExcel = $PHPReader->load($filePath); //加载文件
        $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
        $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
        $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
        $maxColumnNumber = \PHPExcel_Cell::columnIndexFromString($allColumn);
        for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
            for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                $fields[] = $val;
            }
        }
        $insert = [];
        for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
            $values = [];
            for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                if (is_object($val)) $val = $val->__toString();
                $values[] = is_null($val) ? '' : $val;
            }
            $row = [];
            $temp = array_combine($fields, $values);
            foreach ($temp as $k => $v) {
                if (isset($fieldArr[$k]) && $k !== '') {
                    $row[$fieldArr[$k]] = $v;
                }
            }
            $row = array_filter($row);//取出空数组
            if (count($row) > 1) {
                if(!isset($row['goods_name']))
                {
                    //代理商的表头
                    $this->error("获取不到商品名称！。表不合格！");
                }
                if(strstr($row['goods_name'],'补差价'))
                {
                    $this->error("第" . $currentRow . '行，订单存在补差价。');
                }
                if (isset($row['xdtime']) && is_float($row['xdtime'])) {
                    //数据过滤
                    $toTimestamp = \PhpOffice\PhpSpreadsheet\Shared\Date::excelToTimestamp($row['xdtime']);
                    $row['xdtime'] = date("Y-m-d", $toTimestamp);
                }
                if (isset($row['order_sn'])) {
                    if ($order_sn = $this->model->get(['order_sn' => $row['order_sn']])) {
                        $this->error("第" . $currentRow . '行，订单号已经存在。' . $row['order_sn']);
                    }
                }
                $insert[] = $row;
            }
        }
        if (!$insert) {
            $this->error(__('No rows were updated').',或取不到数据，请检查表。');
        }
        return $insert;
    }

    public function send($ids = null)
    {
        //获取过滤需要发送的短信数据
//        print_r($ids);exit;
        echo $lastId = $this->model->max('id');exit;
        $this->bjMergeOrder(1);
        return $this->view->fetch();
    }

    /**
     * 下册订单发货
     */
    public function importwlx()
    {
        ini_set('max_execution_time', '0');
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        $PHPReader = new \PHPExcel_Reader_Excel2007();
        if (!$PHPReader->canRead($filePath)) {
            $PHPReader = new \PHPExcel_Reader_Excel5();
            if (!$PHPReader->canRead($filePath)) {
                $PHPReader = new \PHPExcel_Reader_CSV();
                if (!$PHPReader->canRead($filePath)) {
                    $this->error(__('Unknown data format'));
                }
            }
        }
        $fieldArr['销售订单号'] = 'order_sn';//订单编号
        $fieldArr['发件人姓名*'] = 'agent_id';//代理商id
        $fieldArr['单号'] = 'courierBut';//快递单号
        $fieldArr['A学习书'] = 'xuexishu'; //A学习书
        $fieldArr['B练习书'] = 'lianxishu';//B练习书
        $fieldArr['C素材书'] = 'cucaishu';//C素材书
        $fieldArr['字词句手册'] = 'zicujushouce';//字词句手册
        $fieldArr['自定义区域1'] = 'pro';//字词句手册
        $fieldArr['年级阅读'] = 'nianjiyuedu';//年级阅读
        $fieldArr['教案'] = 'jiaoan';//教案
        $fieldArr['数学'] = 'shyxue';//数学
        $fieldArr['发件人详细地址*'] = 'address';//address
        $fieldArr['备注'] = 'import_note';//remake
        $fieldArr['缺货'] = 'products';//缺货
        $fieldArr['补货'] = 'productb';//补货
        $fieldArr['短信1=自动发送2=手动发送'] = 'sms';//短信

        $PHPExcel = $PHPReader->load($filePath); //加载文件
        $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
        $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
        $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
        $maxColumnNumber = \PHPExcel_Cell::columnIndexFromString($allColumn);
        for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
            for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                $fields[] = $val;
            }
        }
        $rowIds = [];
        $update = [];
        $data = [];
        $num = 0;
        $nums = 0;
        Db::startTrans();
        $error = [];
        $smsArray = [];
        $tifenchaoshi = ['name'=>$this->auth->username,'info'=>[]];
        //如有异常抛出
        try {
            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : $val;
                }
                $row = [];
                $temp = array_combine($fields, $values);
                foreach ($temp as $k => $v) {
                    if (isset($fieldArr[$k]) && $k !== '') {
                        $row[$fieldArr[$k]] = $v;
                    }
                }
                if (!isset($row['order_sn'])) {
                    $this->error(__('订单编号标题错误 ~'));
                }
                if (!isset($row['agent_id'])) {
                    $this->error(__('代理商ID标题错误 ~'));
                }
                if (!isset($row['products']) || !isset($row['productb'])) {
                    $this->error(__('请使用最新的导入模板 ~'));
                }
                if (!isset($row['courierBut'])) {
                    $this->error(__('请填写订单编号 ~'));
                }else{
                    $row['courierBut'] = str_replace('="','',$row['courierBut']);
                    $row['courierBut'] = str_replace('"','',$row['courierBut']);
                }
                $row = array_filter($row);

                if ($row) {
                    if(!isset($row['sms']))
                    {
                        $row['sms'] = 0;
                    }
                    if($row['sms'] == 2)
                    {
                        $row['sms'] = 3;
                    }else{
                        $row['sms'] = 0;
                    }
                    $row['product'] = '';
                    $row['deliveryForm'] = '韵达快递';
                    $smsArray[] = $this->sms($row);
                }
                if (isset($row['agent_id'])) {
                    //学习书 kumu 11  练习书 kumu 12  素材书 kemu13 教案 kemu14 年级阅读 kumu 15  字词句手册 kumu  16
                    $row['agent_id'] = str_replace('宏达一甲','',$row['agent_id']);
                }
                if (isset($row['xuexishu'])) {
                    //学习书 kumu 11  练习书 kumu 12  素材书 kemu13 教案 kemu14 年级阅读 kumu 15  字词句手册 kumu  16
                    $this->getAuthType($row['xuexishu'],11,$row['order_sn'],'学习书');
                    $row['product'] .= $row['xuexishu'] . ',';
                    unset($row['xuexishu']);
                }
                if (isset($row['lianxishu'])) {
                    $this->getAuthType($row['lianxishu'],12,$row['order_sn'],'练习书');
                    $row['product'] .= $row['lianxishu'] . ',';
                    unset($row['lianxishu']);
                }
                if (isset($row['cucaishu'])) {
                    $this->getAuthType($row['cucaishu'],13,$row['order_sn'],'素材书');
                    $row['product'] .= $row['cucaishu'] . ',';
                    unset($row['cucaishu']);
                }
                if (isset($row['zicujushouce'])) {
                    $this->getAuthType($row['zicujushouce'],16,$row['order_sn'],'字词句手册');
                    unset($row['zicujushouce']);
                }
                if (isset($row['nianjiyuedu'])) {
                    $this->getAuthType($row['nianjiyuedu'],15,$row['order_sn'],'年级阅读');
                    $row['product'] .= $row['nianjiyuedu'] . ',';
                    unset($row['nianjiyuedu']);
                }
                if (isset($row['jiaoan'])) {
                    $this->getAuthType($row['jiaoan'],14,$row['order_sn'],'教案');
                    $row['product'] .= $row['jiaoan'] . ',';
                    unset($row['jiaoan']);
                }
                if (isset($row['shyxue'])) {
                    $this->getAuthType($row['shyxue'],'',$row['order_sn'],'数学');
                    $row['product'] .= $row['shyxue'] . ',';
                    unset($row['shyxue']);
                }
                if ($row) {
                    $code = explode(',', $row['product']);
                    $code = array_filter(array_unique($code));
                    if (count($code) > 0) {
                        $result = $this->getAddress($row['address']);
                        $diqu = str_replace("省", "", str_replace(" ", '', trim($result['result']['address_components']['province'])));
                        $diqu .= str_replace("市", "", str_replace(" ", '', trim($result['result']['address_components']['city'])));
                        $diqu .= $result['result']['address_components']['district'];
                        unset($row['address']);
                        foreach ($code as &$value) {
                            $coddeError = $value;
                            $value = str_replace("-", "", str_replace(" ", '', trim($value)));
                            if ($serial = Serial::get(['code' => $value, 'send' => 0])) {
                                $serial->fahuo = $diqu;
                                $serial->sendtime = time();
                                $serial->dealer_uid = $row['agent_id'];
                                $serial->send = 1;
                                $serial->order_sn = $row['order_sn'];
                                $nums += $serial->save();
                            } else {
                                $error[] = $coddeError;
                            }
                        }
                    }

                    if (!isset($row['courierBut'])) {
                        Db::rollback();
                        $this->error(__('第'.$currentRow.'行，请输入快递单号！'));
                    }
                    $update[] = $row;
                    $row['courierBut'] = $this->decimalNotation($row['courierBut']);
                    $ordersntmp = array_filter(explode(',',$row['order_sn']));
                    foreach ($ordersntmp as $item)
                    {
                        if (!$rowGet = $this->model->get(['order_sn' => trim($item)])) {
                            Db::rollback();
                            $this->error(__('订单编号:' . $item . '不存在！'));
                        }
                        if($rowGet->state == 10 || $rowGet->state == 11)
                        {
                            $this->error(__('第'.$currentRow.'行订单号：'.$item.'申请退货或已经退货完成，请拦截此包裹！'));
                        }
                        if (isset($row['import_note'])) {
                            $rowGet->remake = $row['import_note'] ? $row['import_note'] : '';
                        }
                        $rowIds[] = $rowGet->id;
                        $rowGet->courierBut .= $row['courierBut'].',';
                        $courierBut = explode(',', $rowGet->courierBut);
                        $courierBut = implode(',',array_filter(array_unique($courierBut)));
                        $rowGet->courierBut = $courierBut.',';
                        $rowGet->deliveryForm =  '韵达快递';
                        $rowGet->orderStatus = 1;
                        $rowGet->save();
                        //提分超市的订单
                        if($rowGet->agent_id == 81)
                        {
                            $tifenchaoshi['info'][] = [
                                'order_id'=>$item,
                                'delivery_type'=>'express',
                                'delivery_name'=>'韵达快运',
                                'delivery_id'=>$row['courierBut'],
                            ];
                        }
                    }
                }
            }
            if (!$update) {
                Db::rollback();
                $this->error(__('No rows were updated'));
            }
            if (!$rowIds) {
                Db::rollback();
                $this->error(__('No rows were updated'));
            }
            //全部成功的时候 在转发发短信
            $wxsms = new \app\admin\model\Wxsms();
            $wxsms->saveAll($smsArray);
        } catch (\think\exception\PDOException $e) {
            //企业微信通知
            $this->wxmsg($e->getMessage());
            $this->error($e->getMessage());
        }
        Db::commit();
        //=====发送提分超市的订单
        if(count($tifenchaoshi['info']) > 0)
        {
            $wxorderApi = new \app\api\controller\WxOrder();
            $wxorderApi->orderSend($tifenchaoshi);
        }
        //========短信发送
        $wxsms = new \app\admin\controller\wx\Wxsms();
        $wxsms->sendList();
        //========短信结束
        if (count($error) > 0) {
            $this->success('成功（' . $nums . '）条' . '失败（' . count($error) . '）条', '', $error);
        }
        $this->success('成功' . $nums . '条');
    }

    protected function getPro($order_sn,$code,$kemu)
    {
        //查询商品
        $pro_id = $this->modelInfo->where('order_sn','in',trim($order_sn))->field('group_concat(wxproduct_id) as pro_id')->find()->pro_id;
        $wxproduct =  new \app\admin\model\Wxproduct();
        $ids = $wxproduct->where('id','in',$pro_id)->field('group_concat(wxpro_ids) as pro_ids')->find()->pro_ids;
        $wxpro =  new \app\admin\model\Wxpro();
        $row = $wxpro->where('id','in',$ids)->where('name','like',"%{$kemu}%")->field('type,fenlei,kemu,banben')->find();
        $cate = new Cate();
        $cateRow = $cate->get($row['banben']);
        if(!$cateRow)
        {
            $this->error('订单号：'.$order_sn.'没有购买此书：'.$kemu);
        }
        $this->insert_sc($code,$cateRow->kemu,$cateRow->banben,$row['fenlei'].','.$row['kemu'].','.$row['banben']);
    }


    /**
     * 判断分类对不对
     * @param $code
     * @param $kemu
     * @return bool
     * @throws \think\exception\DbException
     */
    protected function getAuthType($code,$kemu,$order_sn,$str)
    {
        $code = str_replace("-", "", str_replace(" ", '', trim($code)));
        $codeArr = array_unique(array_filter(explode(',',$code)));
        foreach ($codeArr as $value)
        {
            if(!$kemu)
            {
                if(!$row = Serial::get(['code'=>$value])){
                    $this->getPro($order_sn,$value,$str);
                }
                if(!in_array($row['kemu'],[23,24,25,26,27,28,29,30,31,32,33,34])){
                    $this->getPro($order_sn,$value,$str);
                }
            }else{
                if(!Serial::get(['banben'=>$kemu,'code'=>$value])){
                    $this->getPro($order_sn,$value,$str);
                }
            }
        }
        return $codeArr;
    }


    /**
     * 财务审核
     * @param null $ids
     */
    public function finance($ids=null)
    {
        if(!$ids) $this->error(__('Parameter %s can not be empty', 'ids'));
        $data  = ['state'=>1];
        if($params = $this->request->param('params')) $data = ['state'=>2,'reason'=>$params];
        $count = $this->model->where('id','in',$ids)->update($data);
        $order_sns = $this->model->where('id','in',$ids)->field('group_concat(order_sn) as order_sns')->find()->order_sns;
        $row = $this->model->where('id','in',$ids)->find();
        if ($count) {
            //添加新的表单
            if($data['state'] == 2)//审核不通过
            {
                \app\admin\model\Wxorder::msg([
                   'moban'=>'ddsh',
                    'order_sn'=>$order_sns,
                    'agent_name'=>Info::getName($row['agent_id']),
                    'id'=>$row['log_id'],
                    'reason'=>$params
                ]);
            }
            //添加新的表单
            if($data['state'] == 1)//审核全部通过
            {
                $count = $this->model->where('log_id','=',$row['log_id'])->where('state','<',8)->count();//通过
                $count1 = $this->model->where('log_id','=',$row['log_id'])->where('state','=',1)->count();//通过
                if($count == $count1)
                {
                    \app\admin\model\Wxorder::msg([
                        'moban'=>'ddsh2',
                        'createtime'=>date('Y-m-d H:i:s',time()),
                        'agent_name'=>Info::getName($row['agent_id']),
                        'id'=>$row['log_id']
                    ]);
                }
            }
            $this->success();
        } else {
            $this->error();
        }
    }

    /**
     * 查看
     */
    public function index($ids = null)
    {
        $row = $this->modelImportLog->get($ids);
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['info'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['info'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            $money = 0;
            $order_sn = $this->model->with(['info'])->where($where)->field('group_concat(order_sn) as order_sns')->find()->order_sns;
            if($order_sn)
            {
                $money = $this->total($order_sn);
            }
            foreach ($list as $row) {
                $row->visible(['id','agent_id','orderStatus','reason','deliveryForm','courierBut','order_sn','xdtime','createtime','gifts','state','amount','receipt','status','akg','phone','address','import_note']);
                $row->visible(['info']);
				$row->getRelation('info')->visible(['agent_name']);

            }
            $list = collection($list)->toArray();
            foreach ($list as &$item) {
                $listInfo = $this->modelInfo->where('order_sn',$item['order_sn'])->select();
                $item['goods_name'] ='';
                foreach ($listInfo as $value)
                {
                    $item['goods_name'] .= $value['goods_name']."[{$value['num']}]";
                }
            }
            $result = array("total" => $total, "rows" => $list, "extend" => ['money' => number_format($money,2), 'price' => 200]);

            return json($result);
        }
        $this->view->assign('ids',isset($row->order_ids) ? $row->order_ids :'');
        return $this->view->fetch();
    }

    /**
     * 统计码洋
     * @param $order_sn
     * @return mixed
     */
    protected function total($order_sn)
    {
        return $this->modelInfo
            ->alias('a')
            ->join('hdyj_wxproduct b','a.wxproduct_id = b.id')
            ->where('order_sn','in',$order_sn)
            ->field('sum(num * ministrial) as nums')
            ->find()->nums;
    }


    /**
     * 申请作废
     * @param $ids
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function become($ids)
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $count = $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            if(!$content = $this->request->param('params')) $this->error('请填写作废原因！');
            $content = explode(':',$content);
            $log = $this->modelImportLog->get(['order_ids'=>$content[1]]);
            $agent_name = Info::getName($log->agent_id);
            $list = $this->model->where($pk, 'in', $ids)->select();
            $count = 0;
            foreach ($list as $k => $v) {
                $v->state = 8;
                $v->zfreason = $content[0];
                $count += $v->save();
            }
            $order_sns = $this->model->where('id','in',$ids)->field('group_concat(order_sn) as order_sns')->find()->order_sns;
            if ($count) {
                \app\admin\model\Wxorder::msg([
                    'moban'=>'ddxg',
                    'id'=>$log->id,
                    'agent_name'=>$agent_name,
                    'order_sn'=>$order_sns,
                    'zfreason'=>$content[0],
                ]);
                $this->success();
            } else {
                $this->error('没有更新任何数据');
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 订单作废
     * @param null $ids
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function becomes($ids = null)
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $count = $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();
            $order_sns = $this->model->where('id','in',$ids)->field('group_concat(order_sn) as order_sns')->find()->order_sns;
            $count = 0;
            $log_id = '';
            $agent_id = '';
            foreach ($list as $k => $v) {
//                $order_sn = 'X';
                if($v->state == 8){
                    $log_id = $v->log_id;
                    $agent_id = $v->agent_id;
                    $v->state = 9;
//                    $v->order_sn = $order_sn.=$v->order_sn;
                    $count += $v->save();
//                    $this->modelInfo->where('order_sn', $order_sn)->update(['order_sn'=>$order_sn]);
                }
            }
            if ($count) {
                \app\admin\model\Wxorder::msg([
                    'moban'=>'ddxg3',
                    'order_sn'=>$order_sns,
                    'agent_name'=>Info::getName($agent_id),
                    'id'=>$log_id
                ]);
                $this->success();
            } else {
                $this->error('没有更新任何数据');
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }


    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    $params['state'] = 3;
                    $text = '';
                    if($row->receipt != $params['receipt'])
                    {
                        $text .= '修改姓名：'.$params['receipt']."  ";
                    }
                    if($row->phone != $params['phone'])
                    {
                        $text .= '修改手机号：'.$params['phone']."  ";
                    }
                    if($row->address != $params['address'])
                    {
                        $text .= '修改地址：'.$params['address']."  ";
                    }
                    if($row->import_note != $params['import_note'])
                    {
                        $text .= '修改备注：'.$params['import_note']."  ";
                    }
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        \app\admin\model\Wxorder::msg([
                            'moban'=>'ddxg2',
                            'id'=>$row->log_id,
                            'order_sn'=>$row->order_sn,
                            'agent_name'=>Info::getName($row->agent_id),
                            'reason'=>$text
                        ]);
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 获取短信内容
     * @param array $row
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function sms($row = array())
    {
        $msg = '';
        if(!isset($row['order_sn']))
        {
            return [];
        }
        $row['order_sn'] = array_filter(explode(',',$row['order_sn']))[0];
        $dataRow = $this->model->get(['order_sn' =>trim($row['order_sn'])]);
        //1.正常订单  缺货 = 空  补货=空 状态=0
        if(!isset($row['products']) && !isset($row['productb']) && $dataRow['status'] == 0)
        {
            $msg =  "【宏达一甲】您的订单{$row['order_sn']}已发货，快递方式：{$row['deliveryForm']}，快递单号：{$row['courierBut']}，请注意查收。";
        }
        //2.缺货  缺货=真  补货=空  状态=0
        if(isset($row['products']) && !isset($row['productb']) && $dataRow['status'] == 0)
        {
            $msg =  "【宏达一甲】您的订单{$row['order_sn']}已发货，{$row['products']}缺货，后期将为您补寄，盼理解。快递方式{$row['deliveryForm']}，快递单号：{$row['courierBut']}，请注意查收。";
        }
        //3.补货  缺货=空  补货=真  状态=0
        if(!isset($row['products']) && isset($row['productb']) && $dataRow['status'] == 0)
        {
            $msg =  "【宏达一甲】为您补寄的{$row['productb']}已发货，订单编号：{$row['order_sn']}，快递方式：{$row['deliveryForm']}，快递单号：{$row['courierBut']}，请注意查收。";
        }
        //return [0 => '正常订单',1 => '已拆订单',2=>'新拆订单',3=>'已合订单',4=>'新合订单'];

        //4.合并订单不缺货   缺货=空  补货=空 状态=4  统计查询合并的订单
        if(!isset($row['products']) && !isset($row['productb']) && $dataRow['status'] == 4)
        {
            //根据收件人姓名 手机号码 创建时间  一致统计出来的订单号
            $order_sn = $this->model->where('status',3)->group('receipt,phone,createtime')->field('group_concat(order_sn) as order_sns')->find();
            $msg =  "【宏达一甲】您的订单{$order_sn['order_sns']}合并为{$row['order_sn']}已经发货，快递方式：{$row['deliveryForm']}，快递单号：{$row['courierBut']}，请注意查收。";
        }
        //5.合并缺货  缺货=真 补货=空 状态=4  统计查询合并的订单
        if(isset($row['products']) && !isset($row['productb']) && $dataRow['status'] == 4)
        {
            //根据收件人姓名 手机号码 创建时间  一致统计出来的订单号
            $order_sn = $this->model->where('status',3)->group('receipt,phone,createtime')->field('group_concat(order_sn) as order_sns')->find();
            $msg =  "【宏达一甲】您的订单{$order_sn['order_sns']}合并为{$row['order_sn']}已经发货，快递方式：{$row['deliveryForm']}，快递单号：{$row['courierBut']}，请注意查收。{$row['products']}缺货，后期将为您补寄，盼理解。";
        }
        //6.合并补货 缺货=空  补货=真 状态=4
        if(!isset($row['products']) && isset($row['productb']) && $dataRow['status'] == 4)
        {
            $msg =  "【宏达一甲】为您补寄的{$row['productb']}已发货，订单编号：{$row['order_sn']}，快递方式：{$row['deliveryForm']}，快递单号：{$row['courierBut']}，请注意查收。";
        }
        //return [0 => '正常订单',1 => '已拆订单',2=>'新拆订单',3=>'已合订单',4=>'新合订单'];

        //7.拆分订单 缺货=空  补货=空 状态=2
        if(!isset($row['products']) && !isset($row['productb']) && $dataRow['status'] == 2)
        {
            $order_sn = array_filter(explode('-',$row['order_sn']));
            $row['order_sn'] = $order_sn[0];
            $msg =  "【宏达一甲】您的订单{$row['order_sn']}已拆分为多个包裹并已发货，快递方式：{$row['deliveryForm']}，快递单号：{$row['courierBut']}，请注意查收";
        }
        //8.拆分缺货 缺货=真  补货=空 状态=2
        if(isset($row['products']) && !isset($row['productb']) && $dataRow['status'] == 2)
        {
            $order_sn = array_filter(explode('-',$row['order_sn']));
            $row['order_sn'] = $order_sn[0];
            $msg =  "【宏达一甲】您的订单{$row['order_sn']}已拆分为多个包裹并已发货，快递方式：{$row['deliveryForm']}，快递单号：{$row['courierBut']}，请注意查收。{$row['products']}缺货，后期将为您补寄，盼理解。";
        }
        //9.拆分补货  缺货=空  补货=真 状态=2
        if(!isset($row['products']) && isset($row['productb']) && $dataRow['status'] == 2)
        {
            $order_sn = array_filter(explode('-',$row['order_sn']));
            $row['order_sn'] = $order_sn[0];
            $msg =  "【宏达一甲】为您补寄的{$row['productb']}已发货，订单编号：{$row['order_sn']}，快递方式：{$row['deliveryForm']}，快递单号：{$row['courierBut']}，请注意查收。";
        }
         return [
             'order_sn'=>trim($row['order_sn']),
             'phone'=>trim($dataRow['phone']),
             'content'=>$msg,
             'send'=>$row['sms']
         ];
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $count = $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();
            $count = 0;
            foreach ($list as $k => $v) {
                $this->modelInfo->where(['order_sn'=>$v->order_sn])->delete();
                $count += $v->delete();
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }


    /**
     * 订单导入
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     * @throws \think\db\exception\BindParamException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function import($ids = null)
    {
        $row = $this->modelImportLog->get(['order_ids'=>$ids]);
        //查询代理商  验证文件
        $agent = Info::get($row['agent_id']);
        if(!$agent['excle_array'])
        {
            $this->wxmsg("《".$agent['agent_name'].'代理商》还没有添加新的模板'."\n操作人：".$this->auth->username."\n 时间：".date('Y-m-d H:i:s',time()));
            $this->error('代理商还没有添加模板数据！');
        }
        $params = $this->request->post("file");
        $filePath = ROOT_PATH . DS . 'public' . DS . $params;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        $createtime = date('Y-m-d H:i:s',time());
        $lastId = $this->model->max('id');
        //获取Excel数据
        $list = $this->upgrade($agent['excle_array'],$filePath);
        //商品名称组装
        $list = $this->GdoodsName($list,$agent['id']);
        //商品规格  数据过滤截取
        list($order,$orderInfo) = $this->filtration($list,$agent['id']);
        // 启动事务
        Db::startTrans();
        try {
            //开启事务回滚
            $this->model->saveAll(array_filter($order));
            $this->modelInfo->saveAll(array_filter($orderInfo));
            // 提交事务
            Db::commit();
            $endtime  = date('Y-m-d H:i:s',time());
            $ids = $this->model->whereTime('createtime','between',[$createtime,$endtime])->field('group_concat(id) as ids')->find()->ids;
            $row->order_ids .=','.$ids;
            $row->save();
            $this->model->where('id','in',$ids)->update(['log_id'=>$row->id]);
            \app\admin\model\Wxorder::msg([
                'moban'=>'dddr',
                'id'=>$row->id,
                'agent_name'=>Info::getName($agent['id']),
                'createtime'=>date('Y-m-d H:i:s',time())
            ]);
            unset($createtime,$endtime);
        } catch (\think\exception\PDOException $exception) {
            // 回滚事务
            Db::rollback();
            $this->wxmsg('订单导入报错：'.$exception->getMessage()."\n操作人：".$this->auth->username."\n 时间：".date('Y-m-d H:i:s',time()));
            $this->error($exception->getMessage());
        }
        $this->view->assign('ids',$row->order_ids);
       $this->success('订单导入成功！<script>window.location.reload()</script>');
    }

    /**
     * 拆分订单
     * 查询当前2分中内添加的订单
     * 查询商品重量大于4千克的需要拆分
     */
    protected function splitOrder($lastId = 0)
    {
        $list = collection($this->model->comment('北京的不需要拆单。查询商品重量大于3.5千克的需要拆分')
            ->alias('a')
            ->join('hdyj_wxorderinfo w','a.order_sn = w.order_sn')
            ->field('a.*,SUM(w.num * w.kg) as akg,SUM(w.num) as anum')
            ->where('a.id','>',$lastId)
            ->where('a.status',0)
            ->where("a.address NOT LIKE '%北京%'")
            ->group('a.order_sn')
            ->having('akg > 3.5')
            ->select())->toArray();
        foreach ($list as $k=>$value)
        {
            //判断需要拆几单
            $numOrder = ceil($value['akg'] / 3.5);
            //拆单数必须 大于等于 商品数 否则不能拆单
            if($numOrder <= $value['anum'])
            {
                $goodsArr = collection($this->modelInfo->where('order_sn',$value['order_sn'])->field('*,SUM(num * kg) as anum')->group('id')->order('anum desc')->select())->toArray();
                $orderinfo = [];
                /**
                 *先拆分在合并，组合
                 *  1.把数量大于1的全部拆分。
                 */
                foreach ($goodsArr as $key=>$goods)
                {
                    if($goods['num'] > 1)
                    {
                        for ($i=1;$i<=$goods['num'];$i++)
                        {

                            $orderinfo[] = [
                                'wxproduct_id'=>$goods['wxproduct_id'],
                                'goods_name'=>$goods['goods_name'],
                                'kg'=>$goods['kg'],
                                'num'=>1,
                                'price'=>$goods['price']
                            ];
                        }
                    }else{
                        $orderinfo[] = [
                            'wxproduct_id'=>$goods['wxproduct_id'],
                            'goods_name'=>$goods['goods_name'],
                            'kg'=>$goods['kg'],
                            'num'=>$goods['kg'],
                            'price'=>$goods['price']
                        ];
                    }
                }
                /**
                 *  组合
                 *  判断最大值加最小值是否大于3.5kg
                 *  大于就不组合，单个商品成一单
                 *  添加数据。
                 */
                $insetOrderInfo = $this->txsf($orderinfo);
                $row = $this->model->get($value['id']);
                $row->status = 1;//变为已拆订单
                $row->save();
                //拼装添加的数据
                unset($value['id'],$value['gifts'],$value['amount'],$value['createtime'],$value['state_text'],$value['status_text'],$value['xdtime_text'],$value['updatetime'],$value['status'],$value['akg'],$value['anum']);
                $value['status'] = 2;//新拆分的订单
                $order_sn = $value['order_sn'];
                $order = [];
                $orderinfo = [];
                foreach ($insetOrderInfo as $key=>$item)
                {
                    $agk = 0;
                    $value['order_sn'] = $order_sn."-".($key+1);

                    foreach ($item as $val)
                    {
                        $agk += $val['kg'];
                        $val['order_sn'] = $value['order_sn'];
                        $orderinfo[] = $val;
                    }
                    $value['akg'] = $agk;
                    $order[] = $value;
                }
                $this->model->saveAll($order);
                $this->modelInfo->saveAll($orderinfo);
            }
        }
    }

    /**
     * 贪心算法
     * @param array $items
     * @return array
     */
    protected function txsf($items = [])
    {
        $source_array = $items;
        $transfer_array = array();

        while (count($source_array) > 0) {
            $max = array_shift($source_array);
            if ($max['kg'] >= 3.5) {
                array_push($transfer_array, array($max));
            } else {
                $temp = array($max);
                foreach ($source_array as $k => $v) {
                    $sum = array_sum(array_column($temp, 'kg'));
                    if (($sum + $v['kg']) <= 3.5) {
                        array_push($temp, $v);
                        unset($source_array[$k]);
                    }
                }
                array_push($transfer_array, $temp);
            }
        }
       return $transfer_array;
        /*
        贪心算法

        $box_volume_count = 3.5; //每个盒 子的最大容积
        $box_count = 0; //共用盒子总数
        $item_count = count($items);
        $box = array();//盒 子数组
        for ($itemindex = 0; $itemindex < $item_count; $itemindex++) {
            $_box_index = false;
            $_box_count = count($box);
            for ($box_index = 0; $box_index < $_box_count; $box_index++) {
                if ($box[$box_index]['volume'] + $items[$itemindex]['kg'] <= $box_volume_count) {
                    $_box_index = $box_index;
                    break;
                }
            }
            if ($_box_index === false) {
                $box[$_box_count]['volume'] = $items[$itemindex]['kg'];
                $box[$_box_count][] = $items[$itemindex];
                $box_count++;
            } else {
                $box[$_box_index]['volume'] += $items[$itemindex]['kg'];
                $box[$_box_index][] = $items[$itemindex];
            }
        }
        return $box;
        */
    }

    /**
     * 合并订单
     * 查询当前2分中内添加的订单
     *
     */
    protected function  mergeOrder($lastId = 0)
    {
        $list = collection($this->model
            ->comment('查询北京以外的重量大于等于3.5的数据')
            ->field('SUM(akg) as akg,xdtime,status,state,weigh,group_concat(order_sn) as cat_ids,count(order_sn) as orders_sn,receipt,phone,address,agent_id')
            ->where('id','>',$lastId)
            ->where( "status = 0 and address NOT LIKE '%北京%'")
            ->group('receipt,phone,address')
            ->having('orders_sn >= 2 and akg <= 3.5 ')
            ->select())->toArray();
        foreach ($list as $value)
        {
            $orderinfo = [];
            $result = collection($this->modelInfo->where('order_sn','in',$value['cat_ids'])->select())->toArray();
            foreach ($result as $key=>$goods)
            {
                if($goods['num'] > 1)
                {
                    for ($i=1;$i<=$goods['num'];$i++)
                    {

                        $orderinfo[] = [
                            'wxproduct_id'=>$goods['wxproduct_id'],
                            'goods_name'=>$goods['goods_name'],
                            'kg'=>$goods['kg'],
                            'num'=>1,
                            'price'=>$goods['price']
                        ];
                    }
                }else{
                    $orderinfo[] = [
                        'wxproduct_id'=>$goods['wxproduct_id'],
                        'goods_name'=>$goods['goods_name'],
                        'kg'=>$goods['kg'],
                        'num'=>$goods['num'],
                        'price'=>$goods['price']
                    ];
                }
            }
            $orderinfo = $this->txsf($orderinfo);
            //长度相等不拆单
            if($value['orders_sn'] == count($orderinfo))
            {
                return false;
            }
            $this->model->where('order_sn','in',$value['cat_ids'])->update(['status'=>3]);
            $order = [];
            $orderinfos = [];
            foreach ($orderinfo as $k=>$value2)
            {
                $agk = 0;
                $value['order_sn'] = 'HB'.time().mt_rand(1,100)."-".$k;
                foreach ($value2 as $v=>$item)
                {
                    $agk += $item['kg'];
                    $item['order_sn'] = $value['order_sn'];
                    $orderinfos[] = $item;
                }
                $value['akg'] = $agk;
                $value['status'] = 4;
                unset($value['cat_ids'],$value['orders_sn'],$value['state_text'],$value['status_text'],$value['xdtime_text']);
                $order[] = $value;
            }
            $this->model->saveAll($order);
            $this->modelInfo->saveAll($orderinfos);
        }
    }

    /**
     * 合并北京订单 没有重量限制
     * @param int $lastId
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function bjMergeOrder($lastId = 0)
    {
        $list = collection($this->model
            ->comment('查询北京的数据进行合并')
            ->field('SUM(akg) as akg,xdtime,status,state,weigh,group_concat(order_sn) as cat_ids,count(order_sn) as orders_sn,receipt,phone,address,agent_id')
            ->where('id','>',$lastId)
            ->where( "status = 0 and address LIKE '%北京%'")
            ->group('receipt,phone,address')
            ->having('orders_sn >= 2 ')
            ->select())->toArray();
        $orderinfo = [];
        $order = [];
        $orderinfos = [];
        foreach ($list as $key=>$value) {
            $result = collection($this->modelInfo->where('order_sn', 'in', $value['cat_ids'])->select())->toArray();
            foreach ($result as $val) {
                $orderinfo[] = [
                    'wxproduct_id'=>$val['wxproduct_id'],
                    'goods_name'=>$val['goods_name'],
                    'kg'=>$val['kg'],
                    'num'=>$val['num'],
                    'price'=>$val['price']
                ];
            }
            $this->model->comment('修改订单状态为3')->where('order_sn','in',$value['cat_ids'])->update(['status'=>3]);
            $agk = 0;
            $value['order_sn'] = 'HB'.time().mt_rand(1,100)."-".$key;
            foreach ($orderinfo as $k=>$value2)
            {
                $agk += ($value2['kg'] * $value2['num']);
                $value2['order_sn'] = $value['order_sn'];
                $orderinfos[] = $value2;
            }
            unset($value['cat_ids'],$value['orders_sn'],$value['state_text'],$value['status_text'],$value['xdtime_text']);
            $value['status'] = 4;
            $value['akg'] = $agk;
            $order[] = $value;
        }
        $this->model->saveAll($order);
        $this->modelInfo->saveAll($orderinfos);
    }

    protected function rsa($row,$productInsert)
    {
        /**
         *  数量* 码洋 = 报价
         *  （没折扣）订单总价 / 取所有商品码洋总价  = 比例 ）    （每一类商品总价 * 折扣 = 含税金额）
         *  (有折扣) 单个商品码洋总价 * 折扣 = 含税金额
         */
        $AgentInfo = Info::get($row['agent_id']);
        $discount_array = $AgentInfo['discount_array'] ? json_decode(unserialize($AgentInfo['discount_array']),true) :[];
        if(count($discount_array) > 1)
        {
            $discount = array_column($discount_array,'discount','dw');//折扣数组
            foreach ($productInsert as &$value)
            {
                if(!isset($discount[$value['unit']]))
                {
                    $this->error('代理商折扣数据跟订单产品不相符。');
                }
                $zhekou = $discount[$value['unit']] / 100;
                $value['lts'] = $zhekou;//折扣
                $value['tax'] = $value['price'] * $zhekou;//折扣
            }
            return $productInsert;
        }
        $mayang = array_sum(array_column($productInsert, 'price'));
        foreach ($productInsert as &$value)
        {
            //没有折扣  表单还没有金额的
            if(!isset($row['amount']))
            {
                $row['amount'] = $mayang;
            }
            if($mayang == 0){
                $this->error($value['goods_name'].'没有码洋价格！');
            }
            $value['lts'] = ($row['amount'] / $mayang);//折扣

            $value['tax'] = $value['price'] * $value['lts'];//扣税金额
        }
        return $productInsert;
    }

    /**
     * 字词句手册验证添加
     * @param null $code
     */
    protected function wordWords($code = null,$banben = '')
    {
        $code = str_replace("-", "", str_replace(" ", '', trim($code)));
        $codeArr = array_unique(explode(',',$code));
        foreach ($codeArr as $value)
        {
            if(!$row = Serial::get(['code'=>$value])){
                Serial::create([
                    'code'=>$value,
                    'product'=>'35',
                    'kemu'=>'11',
                    'banben'=>'16',
                    'type'=>'8,9,28',
                ]);
            }else{
                if($row['banben'] != $banben){
                    $newkeyStr= substr($value, 0, 3);
                    $newkey= $newkeyStr . '-' . substr($value, 3, 5). '-' . substr($value, 8);
                    $this->error($newkey.'不是字词句手册！','','',8);
                }
            }
        }
    }

    protected function getAddress($address)
    {
        $address = urlencode($address);
        $url = "https://apis.map.qq.com/ws/geocoder/v1/?address={$address}&key=HRABZ-YBNW5-5IPIE-QYAY4-7FOP2-2LBID";
        $result = json_decode(\fast\Http::get($url), true);
        if($result['status'] != 0 )
        {
            if($result['status'] == 347)
            {
                $this->error('收货地址错的太离谱了！找不到这个地址:'.urldecode($address));
            }
            $result = $this->getAddress($address);
        }
        return $result;
    }

    /*还原科学计数*/
    protected function decimalNotation($num)
    {
        $parts = explode('E', $num);
        if (count($parts) != 2) {
            return $num;
        }
        $exp = abs(end($parts)) + 3;
        $decimal = number_format($num, $exp, '.', '');
        $decimal = rtrim($decimal, '0');

        return rtrim($decimal, '.');
    }

    /**
     * 上册序列号验证添加
     * @param null $code
     */
    protected function insert_sc($code = null,$kemu='',$banben = '',$type= '')
    {
        $code = str_replace("-", "", str_replace(" ", '', trim($code)));

        if(!$row = Serial::get(['code'=>$code])){
            Serial::create([
                'code'=>$code,
                'product'=>'35',
                'kemu'=>$kemu,
                'banben'=>$banben,
                'type'=>$type,
            ]);
        }
    }

    /**
     * 上册序列号获取分类
     * @param null $code
     */
    protected function gettype_sc($subject=null,$kemu)
    {
        switch($subject){
            case 11:
                if($kemu==11){
                    return $type="8,9,23";
                }elseif($kemu==12){
                    return $type="8,9,24";
                }elseif($kemu==13){
                    return $type="8,9,25";
                }elseif($kemu==14){
                    return $type="8,9,26";
                }elseif($kemu==15){
                    return $type="8,9,27";
                }elseif($kemu==11){
                    return $type="8,9,28";
                }
                break;
            case 13:
                if($kemu==11){
                    return $type="8,38,39";
                }elseif($kemu==12){
                    return $type="8,38,40";
                }elseif($kemu==13){
                    return $type="8,38,41";
                }elseif($kemu==14){
                    return $type="8,38,42";
                }elseif($kemu==15){
                    return $type="8,38,43";
                }elseif($kemu==11){
                    return $type="8,38,44";
                }
                break;
            case 15:
                if($kemu==11){
                    return $type="8,52,53";
                }elseif($kemu==12){
                    return $type="8,52,54";
                }elseif($kemu==13){
                    return $type="8,52,55";
                }elseif($kemu==14){
                    return $type="8,52,56";
                }elseif($kemu==15){
                    return $type="8,52,57";
                }elseif($kemu==11){
                    return $type="8,52,58";
                }
                break;
            case 17:
                if($kemu==11){
                    return $type="8,66,67";
                }elseif($kemu==12){
                    return $type="8,66,68";
                }elseif($kemu==13){
                    return $type="8,66,69";
                }elseif($kemu==14){
                    return $type="8,66,70";
                }elseif($kemu==15){
                    return $type="8,66,71";
                }elseif($kemu==11){
                    return $type="8,66,72";
                }
                break;
            case 19:
                if($kemu==11){
                    return $type="8,80,81";
                }elseif($kemu==12){
                    return $type="8,80,82";
                }elseif($kemu==13){
                    return $type="8,80,83";
                }elseif($kemu==14){
                    return $type="8,80,84";
                }elseif($kemu==15){
                    return $type="8,80,85";
                }elseif($kemu==11){
                    return $type="8,80,86";
                }
                break;
            case 21:
                if($kemu==11){
                    return $type="8,94,95";
                }elseif($kemu==12){
                    return $type="8,94,96";
                }elseif($kemu==13){
                    return $type="8,94,97";
                }elseif($kemu==14){
                    return $type="8,94,98";
                }elseif($kemu==15){
                    return $type="8,94,99";
                }elseif($kemu==11){
                    return $type="8,94,100";
                }
                break;
        }
    }

    public function  orderSn()
    {
        $list = $this->model->where('length(courierBut)>14')->select();
        foreach ($list as $item)
        {
            //有逗号就去重
            if(strpos($item->courierBut,',') !== false)
            {
                $item->courierBut = str_replace('"','',$item->courierBut);
                $item->courierBut = str_replace('=','',$item->courierBut);
                $courierBut = explode(',', $item->courierBut);
                $courierBut = implode(',',array_filter(array_unique($courierBut)));
                $item->courierBut = $courierBut.',';
                $item->save();
            }else{
                //截取字符串
                $arr = [];
                $length2 = strlen($item->courierBut) / 13;
                for ($s=0;$s<=$length2;$s++){
                    $arr[] = substr($item->courierBut,$s*13,13);
                }
                $arr = array_filter($arr);
                $item->courierBut = implode(',',$arr);
                $item->save();
            }
        }
        exit;
    }
}
